/*
 * Create a class to understand hash tables a little better.
 * 
 * Assumptions:
 * 1. Can't add more items them the size of the array (NUM_VALUES).
 * 2. Can't search for a value that has not been added.
 * 
 */
public class HashTable
{
    private static final int NUM_VALUES = 20;
    
    private String[] data;
    private int arraySize;
    
    public static void main(String[] ags) {

        HashTable ht = new HashTable();
        
        /*for(int i = 0; i < (numValuesToEnter ); i++) {
            ht.addItem(String.valueOf(i));
            i += 2;
        }*/
        
        String[] array = { "1", "2", "3", "4", "5",
                           "6", "7", "8", "9", "10",
                           "11", "12", "13", "14", "15",
                           "16", "17", "18", "19", "20" };
        ht.addItems(array);
        
        ht.display();
        
        ht.findItem("19");
        ht.findItem("20");
        ht.findItem("21");
    }
    
    public HashTable() {
        createHashArray(NUM_VALUES);
    }

    private void createHashArray(int size) {
        this.arraySize = size;
        this.data = new String[size];
    }
    
    public void addItem(String item) {
        String value = item;
        this.data[Integer.valueOf(value)] = value;
    }
    
    public void addItems(String[] items) {
        for(int i = 0; i < items.length; i++) {
            String newValue = items[i];
            
            int index = Integer.parseInt(newValue) % NUM_VALUES;
            
            while(data[index] != null) {
                ++index;

                System.out.println("Collision occured, going to try index: " + index);
                
                index %= arraySize;
            }
            
            data[index] = newValue;
        }
    }
    
    public String findItem(String item) {
        String returnValue = null;
        
        int hashIndex = Integer.parseInt(item) % NUM_VALUES;
        
        while(data[hashIndex] != null) {
            if(data[hashIndex] == item) {
                System.out.println("Value was found in index: " + hashIndex);
                
                returnValue = data[hashIndex];
                break;
            }
            
            ++hashIndex;
            
            // Ensure we reset index if array size is reached.
            hashIndex %= arraySize;
        }
        
        return returnValue;
    }
    
    /*
     * Method to display the array values.
     */
    public void display() {
        
        int i = 0;
        System.out.println("-----------------------------------------------------");
        for(String string : data) {
            System.out.println("elem " + i + ": " + string);
            i++;
        }
        System.out.println("-----------------------------------------------------");
    }

}
